package com.yx.gsyd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.liujiebang.pay.wx.entity.WxUserInfo;
import com.yx.gsyd.entity.WxUser;
import com.yx.gsyd.mapper.WxUserMapper;
import com.yx.gsyd.service.IWxUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-06-29
 */
@Service
public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUser> implements IWxUserService {


    /**
     * 注册或者更新用户
     * @param wxUserInfo
     * @return
     */
    @Transactional
    @Override
    public WxUser saveOrUpdateWxUser(WxUserInfo wxUserInfo) {
        WxUser wxUser=this.getOpenId(wxUserInfo.getOpenid());
        if(wxUser!=null){
            //进行更新操作
            wxUser.setUpdatetime(new Date());
            wxUser.setNickName(wxUserInfo.getNickname());
            wxUser.setNickUrl(wxUserInfo.getHeadimgurl());
            this.updateById(wxUser);
        }else{
            wxUser=new WxUser();
            wxUser.setAddtime(new Date());
            //wxUser.setUserId(IdentityUtil.identityId("US"));
            wxUser.setOpenId(wxUserInfo.getOpenid());
            wxUser.setNickName(wxUserInfo.getNickname());
            wxUser.setNickUrl(wxUserInfo.getHeadimgurl());
            //保存用户信息操作
            this.save(wxUser);
        }
        return wxUser;
    }


    /**
     * 根据openId获取用户信息
     * @param openId
     * @return
     */
    @Override
    public WxUser getOpenId(String openId) {
        QueryWrapper<WxUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("open_id",openId);
        WxUser wxUser=this.getOne(queryWrapper);
        return wxUser;
    }


}
